package com.shuai.jit.security.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuai.jit.entity.R;
import com.shuai.jit.entity.user.User;
import com.shuai.jit.security.entity.SecurityUser;
import com.shuai.jit.utils.JwtUtil;
import com.shuai.jit.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Slf4j
public class MyUsernamePasswordFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private JwtUtil jwtUtils;
    private RedisTemplate<String,Object> redisTemplate;

    public MyUsernamePasswordFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtils, RedisTemplate<String,Object> redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        // 设置登录的
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/user/login","POST"));
    }

    /**
     *获取数据库和密码，
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {

            // json 格式的数据转换成  user 对象
            User user = new ObjectMapper().readValue(req.getInputStream(), User.class);

            // 这里是使用 jwtUserDetails 中查找出来的 password 和前端查过来的  password 进行比较
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录成功后，进行的请求
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        SecurityUser user = (SecurityUser) auth.getPrincipal();

        //生成token
        String token = jwtUtils.sign(user.getCurrentUserInfo().getUsername());
        //把权限 放入redis
        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
        //返回
        ResponseUtil.out(res, R.ok().data("token", token));
    }

    /**
     * 登录失败
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, R.error());
    }
}
